package com.lw.leetcode.arr.b;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 1743. 从相邻元素对还原数组
 *
 * @author liw
 * @version 1.0
 * @date 2021/7/25 17:39
 */
public class RestoreArray {

    public static void main(String[] args) {
        RestoreArray test = new RestoreArray();
//        int[][] arr = {{2,1},{3,4},{3,2}};
        int[][] arr = {{4, -2}};

        int[] ints = test.restoreArray(arr);
        System.out.println(Arrays.toString(ints));

    }

    public int[] restoreArray(int[][] adjacentPairs) {
        int length = adjacentPairs.length + 1;
        if (length == 2) {
            return adjacentPairs[0];
        }
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int[] arr : adjacentPairs) {
            List<Integer> list = map.computeIfAbsent(arr[0], item -> new ArrayList<>(2));
            list.add(arr[1]);
            list = map.computeIfAbsent(arr[1], item -> new ArrayList<>(2));
            list.add(arr[0]);
        }

        int a = 0;
        int b = 0;
        for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
            if (entry.getValue().size() == 1) {
                a = entry.getKey();
                b = entry.getValue().get(0);
            }
        }

        int[] values = new int[length];
        int i = 0;
        values[i++] = a;
        values[i++] = b;
        while (i < length) {
            List<Integer> list = map.get(b);
            values[i] = list.get(0) == a ? list.get(1) : list.get(0);
            a = b;
            b = values[i++];
        }
        return values;
    }

}
